package com.rongzhong.routing.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Configuration {

	private static final Properties Props = new Properties();
	private static Logger log = LoggerFactory.getLogger(Configuration.class);
	private static final Configuration instance = new Configuration();

	public Configuration() {
		init();
	}

	public static Configuration getInstance(){
		return instance;
	}
	
	private void init(){
		String configFile = "config/config.properties";
		File file = new File(configFile);
		InputStream is = null;
		try {
			is = new FileInputStream(file);
			if(is != null){
				Props.load(is);
			}
		} catch (FileNotFoundException e) {
			log.error("init run into error.",e);
		} catch (IOException e) {
			log.error("init run into error.",e);
		}finally{
			try{
				if (is != null) {
					is.close();
				}else {
					log.error("can't read the config.properties");
				}
			}catch(IOException e){
				log.error("init run into error.",e);
			}
		}
	}
	
	public String get(String key) {
		return Props.getProperty(key);
	}

	public String get(String key, String defaultValue) {
		return Props.getProperty(key,defaultValue);
	}

	public int getInt(String key, int defaultValue) {
		String value = get(key);
		if (!"".equals(value) && value != null) {
			return Integer.parseInt(value);
		}
		return defaultValue;
	}

	public long getLong(String key, long defaultValue) {
		String value = get(key);
		if (!"".equals(value) && value != null) {
			return Long.parseLong(value);
		}
		return defaultValue;
	}

	public boolean getBoolean(String key, boolean defaultValue) {
		String value = get(key);
		if (value == null) {
			return defaultValue;
		}
		if (value.equalsIgnoreCase("true")) {
			return true;
		} else if (value.equalsIgnoreCase("false")) {
			return false;
		}
		return defaultValue;
	}

	public int getDatabaseNum() {
		return getInt("routingInspection.database.num", 4);//(0-3)
	}
	
	public int getDatabaseCheckNum() {
		return getInt("routingInspection.database.checkNum", 3);//(0-2)
	}
	
	public int getStorageDBIndex() {
		return getInt("routingInspection.database.storageDBIndex", getDatabaseNum() -1); 
	}
	
	public int getMasterDBIndex(){
		return getInt("routingInspection.database.masterDBIndex", 0); 
	}
	
	public String getExcel(){
		return "config/" + get("routingInspection.database.excel","mysql_report.xls");
	}
	
	public String getTableSchema(){
		return get("routingInspection.database.tableschema","test");
	}
	
	public String getDBHostPort(int dbIndex){
		return get("routingInspection.database.hostPort_" + dbIndex,"127.0.0.1_3306");
	}
}
